
class Product
  include DataMapper::Resource

  # property <name>, <type>
  property :id, Serial
  property :name, String
  property :price, Float
  property :price_type, String
  property :price_small, Float
  property :price_big, Float
  property :mod_date, DateTime
  property :type, String
  property :description, String
  property :image , String

  belongs_to :account

  def self.for_account(account)
    p =Product.new
    p.account = account
    p
  end

  # Return "cant" products sorted by pay_date
  def self.get_last_sorted(cant)
    products = Product.all()
    return (products.sort! { |a,b| a.mod_date <=> b.mod_date })[0..cant-1]
  end

  def self.get_last_sorted_type(cant, account_id,tp)
    products = Product.all(:account_id => account_id, :mod_date.gte => Date.today, :type => tp)
    return (products.sort! { |a,b| a.mod_date <=> b.mod_date })[0..cant-1]
  end
  
  def self.update_with_increased_date(account_id, name,type, newname, newtype, newptype,newDesc,newimg)
    prod = Product.find_by_account_id_and_name_and_type(account_id, name, type)

    new_date = Date.today
    payed.mod_date = new_date
    prod.name = newname
    prod.type = newtype
    prod.price_type = newptype
    prod.description = newDesc
    prod.image = newimg 
    return payed
  end
  
  # Params are strings
  def self.create(current_account, name, price, ptype, priceSmall, priceBig, mdate, type, description,img)
    repeated = Product.all(:account_id => current_account.id)
    .first(:name => name, :type => type)

    raise TransactionRepeated if repeated != nil

    product = Product.for_account(current_account)
    product.mod_date = mdate
    product.type = type
    
    product.name = name
    product.price = price
    product.price_type = ptype
    product.price_small = priceSmall
    product.price_big = priceBig
    product.image = img
    product.description = description

    raise TransactionError.new(product.get_error_message) if !product.validate_fields
    return product
  end

  def check_date
    return self.mod_date.is_a?(Date) && self.mod_date >= Date.today
  end

  def check_price
    return (self.price.is_a?(Float)) && (price > 0)
  end

  def check_name
    return (self.name != nil) && not(self.name.strip.empty?)
  end

  def validate_fields
    return check_price && check_date && check_name 
  end

  def get_error_message

    if !check_name
      return "Error, name is required"
    elsif !check_date
      return "Error, invalid date"
    elsif !check_price
      return "Error, invalid amount"
    elsif !check_periodicity
      return "Error, invalid periodicity"
    end
  end

end
